<template>
  <div class="page-container">
    <div class="in-container">
      <AppSearchForm @submit="search" @reset="reset">
        <el-form-item>
          <el-input
            v-model="query.name"
            clearable
            placeholder="输入文件描述模糊搜索"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="query.date"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
      </AppSearchForm>
      <div class="btn-box">
        <el-button icon="el-icon-upload" type="primary" @click="openUpload">
          上传
        </el-button>
      </div>
      <AppPageTable
        stripe
        :data="tableData.data"
        @change="getList"
        :autostyle="'height: calc(100% - 81px);'"
        :option="tableData.option"
      >
        <el-table-column prop="description" label="文件描述">
          <template #default="scope">
            <el-popover
              :content="scope.row.filePath"
              placement="top-start"
              title="路径"
              width="200"
              trigger="hover"
            >
              <template #reference>
                <a
                  :href="baseApi + scope.row.filePath"
                  class="in-link"
                  target="_blank"
                >
                  {{ scope.row.description }}
                </a>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="预览图">
          <template #default="scope">
            <el-image
              :src="baseApi + scope.row.filePath"
              :preview-src-list="[baseApi + scope.row.filePath]"
              fit="cover"
              lazy
              class="el-avatar"
            >
              <template #error>
                <el-icon>
                  <Document />
                </el-icon>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="contentType" label="文件类型" />
        <el-table-column prop="contentTypeName" label="文件类别" />
        <el-table-column prop="size" label="文件大小" />
        <el-table-column prop="createBy" label="创建人" />
        <el-table-column prop="createTime" label="创建日期" />
        <!--   编辑与删除   -->
        <el-table-column label="操作" width="100px" fixed="right">
          <template #default="scope">
            <el-button @click="updateFile(scope.row)" link type="primary"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除本条数据吗？"
              @confirm="deleteFile(scope.row)"
            >
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </AppPageTable>
    </div>
  </div>
  <el-dialog
    v-model="dialogData.show"
    :close-on-click-modal="false"
    :title="dialogData.title"
    width="500px"
  >
    <el-form
      ref="uploadForm"
      :model="form"
      size="small"
      label-width="80px"
      :rule="rules"
    >
      <el-form-item label="文件描述" prop="description">
        <el-input v-model="form.description" />
      </el-form-item>
      <!--   上传文件   -->
      <el-form-item label="上传" v-show="isCreate">
        <el-upload
          ref="upload"
          class="upload-demo"
          :limit="1"
          :before-upload="beforeUpload"
          :auto-upload="false"
          :headers="headers"
          :on-success="handleSuccess"
          :on-error="handleError"
          :action="`${uploadApi}?description= ${form.description}`"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            <em>添加文件</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">请添加文件进行上传,限制最大为100MB</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelUpload" link>取消</el-button>
        <el-button
          type="primary"
          @click="upload"
          :loading="dialogData.btnLoading"
        >
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent } from "vue";
import AppSearchForm from "@/components/AppSearchForm.vue";
import AppTitleBox from "@/components/AppTitleBox.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import dayjs from "dayjs";
export default defineComponent({
  components: {
    AppSearchForm,
    AppPageTable,
    AppTitleBox,
  },
  data() {
    return {
      //查询数据
      query: {
        name: "",
        date: [],
      },
      //表格数据
      tableData: {
        data: [],
        option: useTableOption(),
      },
      //弹窗数据
      dialogData: {
        show: false,
        title: "文件上传",
        btnLoading: false,
      },
      //表单数据
      form: {
        description: "",
      },
      //表单规则
      rules: {
        description: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
      },
      baseApi: import.meta.env.VITE_APP_HOST,
      uploadApi: import.meta.env.VITE_APP_HOST + "/api/storage/upload",
      headers: { Authorization: localStorage.getItem("jst:token") },
      isCreate: false,
    };
  },
  methods: {
    search() {
      this.tableData.option.page = 1;
      this.getList();
    },
    getList() {
      let url = "/api/storage/query";
      if (this.query.date && this.query.date.length > 0) {
        this.query.date[0] = dayjs(this.query.date[0]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.query.date[1] = dayjs(this.query.date[1])
          .add(1, "day")
          .subtract(1, "second")
          .format("YYYY-MM-DD HH:mm:ss");
        url =
          url +
          `?CreateTime=${this.query.date[0]}&CreateTime=${this.query.date[1]}`;
      }
      this.tableData.option.loading = true;
      this.$http
        .get(url, {
          PageIndex: this.tableData.option.page,
          PageSize: this.tableData.option.pageSize,
          KeyWords: this.query.name,
        })
        .then((res) => {
          this.tableData.data = res.content;
          this.tableData.option.total = res.totalElements;
        })
        .catch((err) => {
          this.$message.error("表格数据请求失败");
        })
        .finally(() => {
          this.tableData.option.loading = false;
        });
    },
    reset() {
      this.query = {
        name: "",
        date: [],
      };
      this.tableData.option.page = 1;
      this.search();
    },
    openUpload() {
      this.dialogData.title = "文件上传";
      this.dialogData.show = true;
      this.isCreate = true;
    },
    updateFile(data) {
      this.isCreate = false;
      this.dialogData.title = "文件编辑";
      this.dialogData.show = true;
      this.form = JSON.parse(JSON.stringify(data));
    },
    deleteFile(data) {
      this.$http
        .post("/api/storage/delete", {
          idArray: [data.id],
        })
        .then((res) => {
          if (res.status) {
            this.$message.success(res.message ?? "成功");
            this.search();
          } else {
            this.$message.error(res.message ?? "失败");
          }
        });
    },
    cancelUpload() {
      this.dialogData.show = false;
    },
    submitUpdate() {
      this.$http.post("/api/storage/edit", this.form).then((res) => {
        this.dialogData.btnLoading = false;
        if (res.status) {
          this.$message.success(res.message ?? "成功");
          this.search();
          this.cancelUpload();
        } else {
          this.$message.error(res.message ?? "失败");
        }
      });
    },
    async upload() {
      await this.$refs.uploadForm.validate()
      this.dialogData.btnLoading = true;
      if (this.isCreate) {
        this.$refs.upload.submit();
      } else {
        this.submitUpdate();
      }
    },
    beforeUpload(file) {
      let isTrue = true;
      isTrue = file.size / 1024 / 1024 < 10;
      if (!isTrue) {
        this.dialogData.btnLoading = false;
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      if (this.form.description === "") {
        isTrue = false;
        this.dialogData.btnLoading = false;
        this.$message.error("请输入文件描述再进行上传！");
      }
      return isTrue;
    },
    handleSuccess(response, file, fileList) {
      this.dialogData.btnLoading = false;
      this.$refs.upload.clearFiles();
      this.$message.success(response.message ?? "上传成功");
      this.reset();
      this.dialogData.show = false;
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message);
      this.$message.error(msg.message);
      this.dialogData.btnLoading = false;
    },
  },
  watch: {
    "dialogData.show"(newVal) {
      if (!newVal) {
        this.form.description = "";
        this.$refs.upload.clearFiles();
        this.$refs.uploadForm.clearValidate();
      }
    },
  },

  created() {
    this.search();
  },
});
</script>

<style lang="scss" scoped>
.btn-box {
  margin-bottom: 8px;
}

.upload-demo {
  // border: 1px dashed #c0ccda;
  // border-radius: 5px;
  // height: 65px;
  // line-height: 45px;
  // width: 368px;
  :deep(.el-upload__tip) {
    text-align: center;
  }
  :deep(.el-upload) {
    display: block;
    border: 1px dashed #c0ccda;
    border-radius: 5px;
  }
}

.in-link {
  word-break: keep-all;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #1890ff;
  font-size: 13px;
  text-decoration: none;
}
</style>
